package com.atguigu.gmall.product.component;

import com.atguigu.gmall.product.config.MinioConfig;
import io.minio.MinioClient;
import io.minio.PutObjectOptions;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.io.InputStream;
import java.util.UUID;


/**
 * minio的所有功能
 */
@Component
public class MinioService {

    @Autowired
    MinioClient minioClient;

    @Autowired
    MinioConfig minioConfig;

//    private static MinioService minioService;

//    @PostConstruct
//    public void init(){
//        minioService = this;
//        minioService.minioConfig = this.minioConfig;
//        minioService.minioClient = this.minioClient;
//    }

    public String upload(InputStream inputStream,String bucketName,String fileName) throws Exception{
        if (StringUtils.isEmpty(bucketName)){
            //给默认位置上传
            bucketName = minioConfig.getDefaultBucket();
        }else{
            if (!minioClient.bucketExists(bucketName)){
                minioClient.makeBucket(bucketName);
            }
        }

        fileName = UUID.randomUUID().toString().replace("-","")+"-"+fileName;

        PutObjectOptions options = new PutObjectOptions(inputStream.available(), -1);
        minioClient.putObject(bucketName,fileName,inputStream,options);

        //返回整个文件路径 url+ bucketName + fileName
        String url = "";
        url = minioConfig.getUrl()+"/"+bucketName+"/"+fileName;

        return url;
    }
}
